# -*- encoding=utf8 -*-
"""
    多进行写入文件
"""
import logging.config
import queue
from logging.handlers import QueueHandler, QueueListener
import os

# 定义三种日志输出格式 开始
# standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
#                   '[%(levelname)s][%(message)s]'
standard_format = '[%(asctime)s][%(processName)s:%(process)d][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]'
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

# 获取项目根目录
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
logfile_dir = os.path.join(project_root, "logs")
os.makedirs(logfile_dir, exist_ok=True)

logfile_name = 'pytest.log'  # log文件名
logfile_path = os.path.join(logfile_dir, logfile_name)

# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format,
            'datefmt': '%Y-%m-%d %H:%M:%S',
        },
        'simple': {
            'format': simple_format
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'simple'
        },
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'filename': logfile_path,  # 日志文件
            'maxBytes': 1024 * 1024 * 5,  # 日志大小 5M
            'backupCount': 5,
            'formatter': 'standard',
            'encoding': 'utf-8',  # 日志文件的编码
        },
    },
    'loggers': {
        '': {
            'handlers': ['default', 'console'],  # log数据既写入文件又打印到屏幕
            'level': 'INFO',
            'propagate': True,  # 向上（更高level的logger）传递
        },
    },
}


def setup_logging():
    logging.config.dictConfig(LOGGING_DIC)
    logger_queue = queue.Queue(-1)  # no limit on size
    queue_handler = QueueHandler(logger_queue)
    listener = QueueListener(logger_queue, logging.FileHandler(logfile_path), respect_handler_level=True)
    listener.start()
    root = logging.getLogger()
    root.addHandler(queue_handler)
    return listener


listener = setup_logging()
logger = logging.getLogger(__name__)
